<%@ page import="java.util.List" %>
<%@ page import="com.social.model.User" %>
<%@ page import="com.social.dao.UserDAO" %>
<%@ page import="java.util.Map" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户推荐系统</title>
    <style>
        .tab-container { margin-bottom: 20px; }
        .tab-buttons button {
            padding: 10px 20px;
            background: #f0f0f0;
            border: 1px solid #ccc;
            cursor: pointer;
            margin-right: 5px;
        }
        .tab-buttons button.active {
            background: #4CAF50;
            color: white;
        }
        .tab-content > div { display: none; }
        .tab-content > div.active { display: block; }
        .user-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .user-info {
            flex-grow: 1;
        }
        .user-name {
            font-size: 16px;
            font-weight: bold;
            color: #333;
        }
        .add-friend-btn {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
        }
        .add-friend-btn:hover {
            background-color: #45a049;
        }
        .add-friend-btn.added {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        #searchResults, #randomResults {
            margin-top: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 10px;
        }
        #searchInput {
            padding: 8px;
            width: 300px;
            border: 1px solid #ddd;
            border-radius: 3px;
        }
    </style>
</head>
<body>
<div class="tab-container">
    <div class="tab-buttons">
        <button onclick="switchTab('search')" class="active">搜索用户</button>
        <button onclick="switchTab('random')">随机推荐</button>
        <button onclick="switchTab('mutual')">共同好友推荐</button>
    </div>

    <div class="tab-content">
        <div id="searchTab" class="active">
            <input type="text" id="searchInput" placeholder="输入昵称搜索"
                   oninput="searchUsers()">
            <div id="searchResults"></div>
        </div>

        <div id="randomTab">
            <button onclick="getRandomRecommendations()">刷新推荐</button>
            <div id="randomResults"></div>
        </div>

        <div id="mutualTab">
            <div class="tab-content-header">
                以下是为您推荐的共同好友：
            </div>
            <div id="mutualResults"></div>
        </div>
    </div>
</div>

<script>
    // 用户数据（根据后台返回的数据构建）
    const allUsers = [
        <%
        UserDAO userDAO = new UserDAO();
        List<User> users = userDAO.getAllUsers();
        for(int i = 0; i < users.size(); i++) {
            User user = users.get(i);
            String nickname = user.getNickname() != null ? user.getNickname() : "";

            // 转义特殊字符
            nickname = nickname
                .replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\'", "\\'")
                .replace("\n", "\\n")
                .replace("\r", "\\r");
        %>
        {
            "id": <%= user.getId() %>,
            "nickname": "<%= nickname %>"
        }<%= (i < users.size()-1) ? "," : "" %>
        <% } %>
    ];



    // 共同好友推荐数据（后台返回的 tjFriend 数据）
    const mutualUsers = [
        <%
        // 从会话中获取 tjFriends
        List<Map<String,Object>> tjFriends = (List<Map<String,Object>>)session.getAttribute("tjFriend");
        if (tjFriends != null && !tjFriends.isEmpty()) {
            for (int i = 0; i < tjFriends.size(); i++) {
                String nickname = tjFriends.get(i).get("nickname") != null ? tjFriends.get(i).get("nickname").toString() : "";

                // 转义特殊字符
                nickname = nickname
                    .replace("\\", "\\\\")
                    .replace("\"", "\\\"")
                    .replace("\'", "\\'")
                    .replace("\n", "\\n")
                    .replace("\r", "\\r");
        %>
        {
            "id": <%= tjFriends.get(i).get("id") %>,
            "nickname": "<%= nickname %>",
            "mutualCount": 0
        }<%= (i < tjFriends.size() - 1) ? "," : "" %>
        <%
            }
        }
        %>
    ];

    // 存储已发送的好友请求
    const sentRequests = new Set();

    // 切换标签页函数
    function switchTab(tabName) {
        console.log("tabName",tabName)
        // 隐藏所有内容区域
        document.querySelectorAll('.tab-content > div').forEach(div => {
            div.classList.remove('active');
        });

        // 激活当前内容区域
        document.getElementById(tabName + 'Tab').classList.add('active');

        // 更新按钮状态
        document.querySelectorAll('.tab-buttons button').forEach(btn => {
            btn.classList.remove('active');
        });
        event.target.classList.add('active');

        // 如果是随机标签页，自动刷新推荐
        if(tabName === 'random') {
            getRandomRecommendations();
        }// 如果是共同好友标签页，显示共同好友推荐
        else if(tabName === 'mutual') {
            showMutualFriends();
        }
    }

    // 搜索用户函数
    function searchUsers() {
        const keyword = document.getElementById('searchInput').value.toLowerCase();

        if(!keyword) {
            document.getElementById('searchResults').innerHTML = '';
            return;
        }

        const results = allUsers.filter(user => {
            const nickname = user.nickname || '';
            return nickname.toLowerCase().includes(keyword);
        });

        displayResults(results, 'searchResults');
    }

    // 获取随机推荐
    function getRandomRecommendations() {
        // 复制数组避免修改原数组
        const shuffled = [...allUsers].sort(() => 0.5 - Math.random());
        const selected = shuffled.slice(0, 3);

        displayResults(selected, 'randomResults');
    }
    // 显示共同好友推荐
    function showMutualFriends() {
        displayMutualResults(mutualUsers, 'mutualResults');
    }
    // 显示结果函数 - 添加加好友按钮
    function displayResults(users, containerId) {
        console.log("user111",users)
        const container = document.getElementById(containerId);
        container.innerHTML = ''; // 清空容器

        if(users.length === 0) {
            const noResult = document.createElement('div');
            noResult.className = 'user-item';
            noResult.textContent = '未找到匹配用户';
            container.appendChild(noResult);
            return;
        }

        users.forEach(user => {
            const userItem = document.createElement('div');
            userItem.className = 'user-item';

            // 用户信息区域
            const userInfo = document.createElement('div');
            userInfo.className = 'user-info';

            const userName = document.createElement('div');
            userName.className = 'user-name';
            const nickname = user.nickname || `(ID: ${user.id}) 未设置昵称`;
            userName.textContent = nickname;

            userInfo.appendChild(userName);
            userItem.appendChild(userInfo);

            // 加好友按钮
            const addButton = document.createElement('button');
            addButton.className = 'add-friend-btn';
            addButton.textContent = '加好友';
            addButton.dataset.userId = user.id;

            // 检查是否已发送请求
            if (sentRequests.has(user.id)) {
                addButton.textContent = '已发送';
                addButton.classList.add('added');
                addButton.disabled = true;
            } else {
                addButton.onclick = function() {
                    addFriend(user.id, this);
                };
            }

            userItem.appendChild(addButton);
            container.appendChild(userItem);
        });
    }
    // 显示共同好友结果（添加共同好友数量显示）
    function displayMutualResults(users, containerId) {
        const container = document.getElementById(containerId);
        container.innerHTML = ''; // 清空容器

        if(users.length === 0) {
            const noResult = document.createElement('div');
            noResult.className = 'user-item';
            noResult.textContent = '暂无共同好友推荐';
            container.appendChild(noResult);
            return;
        }

        users.forEach(user => {
            const userItem = document.createElement('div');
            userItem.className = 'user-item';

            // 用户信息区域
            const userInfo = document.createElement('div');
            userInfo.className = 'user-info';

            const userName = document.createElement('div');
            userName.className = 'user-name';
            const nickname = user.nickname || `(ID: ${user.id}) 未设置昵称`;
            userName.textContent = nickname;

            userInfo.appendChild(userName);

            // 显示共同好友数量
            

            userItem.appendChild(userInfo);

            // 加好友按钮
            const addButton = document.createElement('button');
            addButton.className = 'add-friend-btn';
            addButton.textContent = '加好友';
            addButton.dataset.userId = user.id;

            // 检查是否已发送请求
            if (sentRequests.has(user.id)) {
                addButton.textContent = '已发送';
                addButton.classList.add('added');
                addButton.disabled = true;
            } else {
                addButton.onclick = function() {
                    addFriend(user.id, this);
                };
            }

            userItem.appendChild(addButton);
            container.appendChild(userItem);
        });
    }
    // 添加好友函数 - 调用后台方法
    function addFriend(userId, buttonElement) {
        console.log(`发送好友请求给用户ID: ${userId}`);

        // 这里调用后台方法（模拟）
        // 实际项目中应使用AJAX调用后端API
        sendFriendRequest(userId);

        // 更新按钮状态
        buttonElement.textContent = '已发送';
        buttonElement.classList.add('added');
        buttonElement.disabled = true;

        // 添加到已发送请求集合
        sentRequests.add(userId);

        // 显示操作反馈
        showNotification("已添加该用户为好友");
    }

    // 发送好友请求到后台（模拟）
    function sendFriendRequest(userId) {
        console.log(`调用后台方法: addFriend(${userId})`);

        //实际AJAX调用示例:
        fetch('/sendAddFriend?friendId='+userId+'&myId=${userId}', {
            method: 'GET',
        });

    }

    // 显示操作通知
    function showNotification(message) {
        // 移除现有通知
        const oldNotification = document.getElementById('notification');
        if (oldNotification) oldNotification.remove();

        const notification = document.createElement('div');
        notification.id = 'notification';
        notification.textContent = message;
        notification.style.position = 'fixed';
        notification.style.top = '20px';
        notification.style.right = '20px';
        notification.style.backgroundColor = '#4CAF50';
        notification.style.color = 'white';
        notification.style.padding = '10px 20px';
        notification.style.borderRadius = '5px';
        notification.style.boxShadow = '0 2px 10px rgba(0,0,0,0.2)';
        notification.style.zIndex = '1000';

        document.body.appendChild(notification);

        // 3秒后自动消失
        setTimeout(() => {
            notification.style.opacity = '0';
            notification.style.transition = 'opacity 1s';
            setTimeout(() => notification.remove(), 1000);
        }, 3000);
    }

    // 页面加载时初始化
    window.onload = function() {
        getRandomRecommendations();
        // 初始化共同好友推荐数据
        showMutualFriends();
    };
</script>
</body>
</html>